package com.scalar.chiptrack.sales.actions.quote;

import java.util.ArrayList;
import java.util.HashMap;
import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.alarms.Alarm;
import com.scalar.chiptrack.alarms.dao.AlarmDAO;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.Quotation;
import com.scalar.chiptrack.sales.SalesOrderHelper;
import com.scalar.chiptrack.sales.actions.SalesOrderAction;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.dao.quote.QuotationDAO;
import com.scalar.chiptrack.sales.forms.quote.QuotationForm;
import com.scalar.chiptrack.users.User;

/**
 * Author: Prabhanjan
 * Date: Feb 19, 2004
 * Time: 6:04:32 PM
 */

public final class ApproveQuotationAction extends ChipTrackAction
{

    private static final String ACTION_NAME = "/approveQuotation.do"; // TBD
    int isSample = 1;

    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response )
            throws Exception
    {

        QuotationForm subform = ( QuotationForm ) form;
        HttpSession session = request.getSession ();

        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
            return ( mapping.findForward ( "login" ) );
        }

        /* Commented by Prabhanjan, Sep 17, 2004
        // Great Plains Sales Integration Re-direction -----------------------------------------
        // Prabhanjan on Feb 24, 2004
        if ( Constants.FINANCE_INTEGRATION_TYPE_GREAT_PLAINS.equalsIgnoreCase ( ConfigManager.getFinanceIntegrationType () ) == true )
        {
            return new GPApproveQuotationAction ().execute ( mapping, form, request, response );
        }
        // Great Plains Re-direction -----------------------------------------------------------
        */

        String action = request.getParameter ( "action" );

        HashMap errors = new HashMap ();
        HashMap info = new HashMap ();

        if ( "approveQuotation".equals ( action ) )
        {
            String quotationId  = request.getParameter ( "quotationId" );
            String isApproved   = request.getParameter ( "isApproved" );
            String quotationNo  = request.getParameter ( "quotationNo" );
            int quotationIdInt  = 0;

            try
            {
                quotationIdInt = Integer.parseInt( quotationId );
            }catch(NumberFormatException nfe){};

            if ( !isTokenValid ( request ) )
            {
                errors.put ( ERROR_SALES_ORDER_ALREADY_SAVED, null );
            }

            resetToken ( request );

            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                saveToken ( request );
                return ( mapping.findForward ( "success" ) );
            }

            DBTransaction dbTransaction = null;
            boolean success = false;
            Alarm alarm = null;

            try
            {
                dbTransaction = DBTransaction.getInstance ();
                dbTransaction.begin ();

                ArrayList lineItems = ( ArrayList ) session.getAttribute ( "lineItems" );

                loadLineItemApprovalStatus ( lineItems, request );

                QuotationDAO.approveQuotationOrderLineItems ( dbTransaction, quotationIdInt, lineItems );

                //alarm = QuotationDAO.updateAlarmForChangeQuotation ( dbTransaction, "", Integer.parseInt ( quotationId ), user );

                request.setAttribute ( "quotationId", quotationId );

                success = true;
            }
            catch ( ScalarException se )
            {
                errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_QUOTATION_DETAILS );
                errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Quote Details " );
                session.setAttribute ( SessionKeys.ERROR_REPORT, se );
            }
            finally
            {
                if ( success == true )
                {
                    dbTransaction.commit ();

                    try
                    {
                        //alarm.setRecipients ( AlarmDAO.loadRecipientsWithChangeQuoteAccess ( alarm ) );
                        //alarm.notifyAllRecipients ( Quotation.getHtmlViewWithChangeSummary ( Integer.parseInt ( quotationId ), "" ) );

                        QuotationDAO.updateAlarmAndSendMailWithChangeSummary( "", quotationIdInt, true, user, "" );
                        QuotationDAO.notifyApprovedQuotationInfo ( quotationIdInt );

                        errors.put ( "Email ", " has been sent to all approvers" );
                    }
                    catch ( Exception e )
                    {
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SENDING_MAILS_TO_APPROVERS );
                        errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                        session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Send Mail to all Approvers " );
                        session.setAttribute ( SessionKeys.ERROR_REPORT, e );
                    }

                    if ( isSample == 1 )
                    {
                        errors.put ( "Quote = " + quotationNo, "Saved Successfully" );
                        errors.put ( "View/Print ", "Click here to <a href='javascript:openQuotation();'onmouseover=\"window.status='Click here to View/print Quatation';return true\" onmouseout=\"window.status='';return true\" > view/print </a> Quote Details" );
                    }
                    else
                    {
                        //errors.put("SampleOrder = " + quotation.getSalesOrderNo(), "Saved Successfully");
                        //errors.put("Email ", " has been send to all approvers");
                        //errors.put("View/Print ","Click here to <a href='javascript:openQuotation();'> view/print </a>Sample Order Details");
                    }
                }
                else
                {
                    dbTransaction.rollback ();

                    errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_QUOTATION_DETAILS );
                    errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                    session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Quote Details " );
                    session.setAttribute ( SessionKeys.ERROR_REPORT, null );
                }
            }

            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.MESSAGES, errors );
                if ( !info.isEmpty () )
                    request.setAttribute ( SessionKeys.INFO_MESSAGES, info );

            }
            session.removeAttribute("lineItems");
            session.removeAttribute("lineItemsWithSubtotals");
        }
        else if ( request.getParameter ( "quotationId" ) != null )
        {
            String quotationId = request.getParameter ( "quotationId" );

            //Loading the quotation details with out its corresponding customer details
            //Modified by Prabhanjan on 12 Feb 2004
            Quotation quotation = QuotationDAO.loadQuotation ( quotationId, false );

            //Loading the customer details pertaining to the customer of this quotation
            Quotation quotationCustomerDetails = QuotationDAO.getQuotationCustomerDetails ( Integer.toString ( quotation.getCustomerId () ) );
            if( ConfigManager.isLoadQuotationQuestionnaire() )
            {
                QuotationDAO.loadQuotationQuestionnaireDetails( null, quotation );
                QuotationDAO.retrieveAttachedFileInformation( quotation );
            }
            request.setAttribute("prevQuotationsList", QuotationDAO.getPrevQuotationDetails(null, quotation.getCustomerId()));
            request.setAttribute("prevQuotationPriceList", QuotationDAO.getPrevQuotationPriceDetails(null, quotation.getCustomerId()));
            request.setAttribute( "prevCommitmentsDetails", QuotationDAO.getPrevCommitmentsDetails(null, quotation.getCustomerId()));
            //Setting the customer details loaded using the above method into the quotation object
            quotation.setShippingMethods ( quotationCustomerDetails.getShippingMethods () );
            quotation.setShippingAddresses ( quotationCustomerDetails.getShippingAddresses () );

            //Copying the properties into the form object
            PropertyUtils.copyProperties ( subform, quotation );

            request.setAttribute ( "shippingMethods", quotationCustomerDetails.getShippingMethods () );
            request.setAttribute ( "shippingAddresses", quotationCustomerDetails.getShippingAddresses () );

            //subform.setShippingMethod ( subform.getShippingMethodName () + "   #   " + subform.getShippingAccount () );

            request.setAttribute ( "QuotationForm", subform );

            ArrayList lineItems = QuotationDAO.loadOrderLineItemsWithCustomerPartNo ( Integer.parseInt ( quotationId ), quotation.getCustomerId () );
            session.setAttribute ( "lineItems", lineItems );

            /*if ( !( subform.getEndUser ().trim ().equals ( "" ) ) )
            {
                SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, lineItems, Integer.parseInt ( subform.getEndUserId () ) );
            }
            else
            {
                SalesOrderDAO.loadCustomerPartNumbersForLineItems ( null, lineItems, subform.getCustomerId (), subform.getOdmId() );
                NewSalesOrderDAO.loadOdmLabelNumbersForLineItems ( null, lineItems, subform.getCustomerId (), subform.getOdmId() );
            }*/
            /*else if (  subform.getOdmId () > 0 )
            {
                SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, lineItems, subform.getOdmId () );
            }*/

            //Added by Prabhanjan on 07 Mar 2004
            session.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );

            request.setAttribute ( "maxLineItemNo", Integer.toString ( QuotationDAO.loadMaxLineItemNo ( quotation.getQuotationId () ) ) );

            request.setAttribute ( "mktgParts", SalesOrderDAO.loadAllMarketingPartNumbers () );
            request.setAttribute ( "mfgParts", SalesOrderDAO.loadAllManfacturingPartNumbers () );
            request.setAttribute ( "mfgPartsWithComments", SalesOrderDAO.loadAllManfacturingPartNumbersWithComments () );

            request.setAttribute ( "salesTaxes", SalesDAO.loadSalesTaxList () );
            request.setAttribute ( "screenDisplayFiledsList", QuotationDAO.getScreenDisplayFiledsList( null ) );

            saveToken ( request );

            return ( mapping.findForward ( "approveQuotation" ) );
        }
        return ( mapping.findForward ( "successQuotation" ) );
    }

    private void loadLineItemApprovalStatus ( ArrayList lineItems, HttpServletRequest request )
    {
        for ( int i = 0; i < lineItems.size (); i++ )
        {
            LineItem lineItem = ( LineItem ) lineItems.get ( i );
            int lineItemNo = lineItem.getLineItemNo ();
            String isApproved = request.getParameter ( "isApproved" + lineItemNo );

            int approveStatus = 0;

            if ( isApproved != null )
            {
                approveStatus = 1;
                String leadTime = request.getParameter ( "leadTime" + lineItemNo );
                lineItem.setLeadTime( leadTime );
            }
            lineItem.setIsApproved ( ( ( approveStatus == 0 ) ? false : true ) );
        }
    }

    public static String state = null;
    public static String s = null;
}
